<script>
export default {
  name: "DkInputNumber",
}
</script>

<script setup>
const props = defineProps({
  precision: {
    type: Number,
    default: 0,
  },
  modelValue: {
    type: [Number, String],
    default: 0,
  },
  // 允许输入负数
  allowNegative: {
    type: Boolean,
    default: false,
  },
  // 整数   待优化
  isInte: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(["change", "update:modelValue"])

const currentValue = computed({
  get: () => {
    return props.modelValue
  },
  set: (value) => {
    emit("update:modelValue", value)
  },
})

const handleBlur = () => {
  const v = currentValue.value
  if (v == "") return
  currentValue.value = v ? Number(v).toFixed(props.precision) : parseFloat("0").toFixed(props.precision)
  // if(currentValue.value == 0) currentValue.value = ''
}

const formatter = (v) => {
  if (props.isInte) {
    return !props.allowNegative ? v.replace(/[^\d]/g, "") : ""
  } else {
    return !props.allowNegative ? v.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1") : ""
  }
}
</script>

<template>
  <el-input style="width: 150px" typ="number" v-bind="$attrs" @blur="handleBlur" v-model="currentValue" :formatter="formatter" />
</template>

<style scoped lang="scss"></style>
